<?php
// +----------------------------------------------------------------------
// | ZGUAN [ 致力于帮助更多的中小企业物联网转型 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2024 https://www.zguan.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ZGUAN 并不是自由软件，未经许可不能去掉ZGUAN 相关版权
// +----------------------------------------------------------------------
// | Author: ZGUAN Team <admin@zguan.cn>  0769-82282996  15899929162
// +----------------------------------------------------------------------
namespace app\common\model\energy;

use app\common\model\BaseModel;
use app\common\model\room\RoomBasicModel;
use app\common\model\bill\BillCatalogModel;
use app\common\model\property\basic\PropertyBasicModel;

class EnergyBillModel extends BaseModel
{
    protected $autoWriteTimestamp = 'datetime';
    protected $createTime = 'add_time';
    protected $updateTime = false;

    public static function tablePk(): string
    {
        return 'id';
    }

    public static function tableName(): string
    {
        return 'energy_bill';
    }

    public function propertyInfo()
    {
        return $this->hasOne(PropertyBasicModel::class, 'id', 'property_id');
    }

    public function roomInfo()
    {
        return $this->hasOne(RoomBasicModel::class, 'id', 'room_id');
    }
    public function energyMeterInfo()
    {
        return $this->hasOne(EnergyMeterModel::class, 'id', 'energy_id');
    }

    public function billCatalogInfo()
    {
        return $this->hasOne(BillCatalogModel::class, 'energy_bill_id', 'id');
    }

    public function getBillCatalogInfoAttr()
    {
        $data = [];
        $data = BillCatalogModel::where('energy_bill_id', $this->id)
            ->with([
                'billBasicInfo' => function ($query) {
                    $query->bind(['bill_number' => 'number']);
                }
            ])
            ->find();
        return $data;
    }

    public function getPlanRecordAttr($value)
    {
        try {
            return json_decode($value, true);
        } catch (\Exception $e) {
            return [];
        }
    }

    public function getTotalAmountAttr()
    {
        return bcadd($this->loss_amount, bcadd($this->basic_amount, $this->service_amount, 2), 2);
    }

}
